/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.anniversary.service.impl;

import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.anniversary.domain.Photos;
import me.zhengjie.modules.anniversary.repository.PhotosRepository;
import me.zhengjie.modules.anniversary.service.PhotosService;
import me.zhengjie.modules.anniversary.service.dto.PhotosDto;
import me.zhengjie.modules.anniversary.service.dto.PhotosQueryCriteria;
import me.zhengjie.modules.anniversary.service.mapstruct.PhotosMapper;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.ValidationUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author Jiayin Wei
* @date 2020-07-27
**/
@Service
@RequiredArgsConstructor
public class PhotosServiceImpl implements PhotosService {

    private final PhotosRepository photosRepository;
    private final PhotosMapper photosMapper;

    @Override
    public Map<String,Object> queryAll(PhotosQueryCriteria criteria, Pageable pageable){
        Page<Photos> page = photosRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(photosMapper::toDto));
    }

    @Override
    public List<PhotosDto> queryAll(PhotosQueryCriteria criteria){
        return photosMapper.toDto(photosRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    /**
     * 查询总数
     * @return Long
     */
    @Override
    public Long count(){
        return photosRepository.count();
    }

    @Override
    @Transactional
    public PhotosDto findById(Long id) {
        Photos photos = photosRepository.findById(id).orElseGet(Photos::new);
        ValidationUtil.isNull(photos.getId(),"Photos","id",id);
        return photosMapper.toDto(photos);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PhotosDto create(Photos resources) {
        return photosMapper.toDto(photosRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Photos resources) {
        Photos photos = photosRepository.findById(resources.getId()).orElseGet(Photos::new);
        ValidationUtil.isNull( photos.getId(),"Photos","id",resources.getId());
        Long oldReviewerId = photos.getReviewerId();
        photos.copy(resources);
        if (oldReviewerId != photos.getReviewerId())
        {
            photos.setReviewTime(new Timestamp(System.currentTimeMillis()));
        }
        photosRepository.save(photos);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            photosRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<PhotosDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (PhotosDto photos : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("名称", photos.getName());
            map.put("上传用户", photos.getUploadUser() == null ? "" : photos.getUploadUser().getUsername());
            map.put("类型（0：全校的民大剪影，1：班级老照片）", photos.getType());
            map.put("院系班级", photos.getDepartment() == null ? "" : photos.getDepartment().getName());
            map.put("拍摄时间", photos.getTime());
            map.put("拍摄地点", photos.getAddress());
            map.put("照片保存地址", photos.getPath());
            map.put("审核状态（0：待审核、1：审核通过、2：审核未通过）", photos.getVerifyStatus());
            map.put("审核者", photos.getReviewer() == null ? "" :photos.getReviewer().getUsername());
            map.put("审核时间",photos.getReviewTime());
            map.put("创建者名称", photos.getCreateBy());
            map.put("创建时间", photos.getCreateTime());
            map.put("修改者名称", photos.getUpdatedBy());
            map.put("修改时间", photos.getUpdateTime());
            map.put("排序", photos.getSort());
            map.put("备注", photos.getRemark());
            map.put("是否启用", photos.getIsEnable());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    /**
     * 首页中的轮播图
     * @param pageable
     * @return
     */
    @Override
    public List<Map<String,Object>> findByRotation(Pageable pageable){
        return photosRepository.findByRotation(pageable);
    }

    /**
     * 分页查询民大剪影中的信息
     * @param pageable
     * @return
     */
    @Override
    public List<Map<String,Object>> findByPhotos(Pageable pageable){
        return photosRepository.findByPhotos(pageable);
    }
}
